// pages/addParking/addParking.js
const app = getApp();
import {
  addRecordApprovalApi,
  findRecordApprovalApi,
  getAddedParkApi,
} from "../../api/index.js";
let timeId = 0;
let timeId2 = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageHeight:0,
    activeTab: 0,
    isRoadOffRequired: false, //路外
    isRoadRequired: false, //路内
    steps: [
      {
        text: "待审批",
      },
      {
        text: "审批中",
      },
      {
        text: "审批拒绝",
      },
      {
        text: "审批通过",
      },
      {
        text: "公示",
      },
    ],
    multipleResult: [],
    showMultiple: false,
    multipleType: null, //多选类型名称
    multipleList: [],
    parkLocationTypeColumns: [
      { value: 1, name: "路内停车场" },
      { value: 2, name: "机动车停车场" },
    ],
    angleTypeColumns: [
      { value: 1, name: "垂直" },
      { value: 2, name: "平行" },
      { value: 3, name: "倾斜" },
    ],
    manageTypeColumns: [
      { value: 1, name: "敞开" },
      { value: 2, name: "封闭" },
      { value: 3, name: "半封闭" },
    ],
    changeTypeColumns: [
      { value: 1, name: "新增" },
      { value: 2, name: "调整" },
      { value: 3, name: "取缔" },
    ],
    jurisdictionColumns: ["裕华区", "桥西区", "长安区", "新华区", "高新区"],
    chargingAreaColumns: [
      { value: 1, name: "核心区" },
      { value: 2, name: "一类区" },
      { value: 3, name: "二类区" },
      { value: 4, name: "三类区" },
    ],
    trafficPoliceColumns: [
      "裕华区交警大队",
      "桥西区交警大队",
      "长安区交警大队",
      "新华区交警大队",
      "高新区交警大队",
    ],
    parkWayColumns: [
      { value: 1, name: "自行自走式" },
      { value: 2, name: "机械存取式" },
      { value: 3, name: "半机械式" },
    ],
    pricingMethodColumns: [
      { value: 1, name: "政府定价" },
      { value: 2, name: "市场调节定价" },
    ],
    buildingTypeColumns: [
      { value: 1, name: "商业" },
      { value: 2, name: "办公" },
      { value: 3, name: "住宅" },
      { value: 4, name: "公共建筑" },
      { value: 5, name: "商住混合" },
      { value: 6, name: "专用停车楼" },
      { value: 7, name: "其他" },
    ],
    parkTypeColumns: [
      { value: 1, name: "规划配建停车场" },
      { value: 2, name: "机械式立体停车场" },
      { value: 3, name: "临时停车场" },
      { value: 4, name: "建筑退线区域停车场" },
      { value: 5, name: "免费停车场" },
      { value: 6, name: "其他" },
    ],
    parkOwnershipColumns: [
      { value: 1, name: "单位" },
      { value: 2, name: "社区" },
      { value: 3, name: "个人" },
      { value: 4, name: "其他" },
    ],
    parkOwnershipTypeColumns: [
      { value: 1, name: "公共" },
      { value: 2, name: "共有" },
      { value: 3, name: "私有" },
    ],
    openClosedTypeColumns: [
      { value: 1, name: "开放式" },
      { value: 2, name: "半封闭式" },
      { value: 3, name: "封闭式" },
    ],
    parkAngleColumns: [
      { value: 1, name: "平行" },
      { value: 2, name: "垂直" },
      { value: 3, name: "倾斜" },
    ],
    intelligentDeviceColumns: [
      { value: 1, name: "机械式立体停车设备" },
      { value: 2, name: "智能引导和收费系统" },
    ],
    reserveTypeColumns: [
      { value: 1, name: "开放式" },
      { value: 2, name: "封闭型" },
    ],
    singleDoubleSystemColumns: [
      { value: 1, name: "单" },
      { value: 2, name: "双" },
    ],
    isAutoPayColumns: [
      { value: 1, name: "支持" },
      { value: 0, name: "不支持" },
    ],
    chargingFlagColumns: ["是", "否"],
    parkManagerId: "",
    type: "add",
    auditStatus: null,
    agreementVip: true,
    btnDisblay: false,
    disabled: false,
    isExist: 1,
    form: {},
    recordApprovalList: [], //我的审批
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.getSystemInfo({
      success: res => {
        // console.log(res)
        //安卓设定的导航栏高度为48px，iOS设定的导航栏高度为44px
        let navHeight = 44
        if (res.system.indexOf('iOS') !== -1) { //判断当前设备是 ios或android
          navHeight = 44
        } else {
          navHeight = 48
        }
        this.setData({
          pageHeight:res.screenHeight-res.statusBarHeight-100
        })
      }
    })

    console.log(options);
    if (options.type) {
      if (options.type === "see" || options.type === "old") {
        this.setData({
          disabled: true,
          isExist: 2,
        });
      }
      this.setData({
        type: options.type,
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      parkManagerId: wx.getStorageSync("userId"),
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearTimeout(timeId);
    clearTimeout(timeId2); //清除定时器
  },

  onChangeTab(event) {
    const { name } = event.detail;
    if (name === 1) {
      this.findRecordApproval();
    }
  },

  // methods
  // 查询备案审批
  async findRecordApproval() {
    const { data: res } = await findRecordApprovalApi({});
    this.setData({
      recordApprovalList: res.data,
    });
  },

  // 输入框输入
  bindKeyInput(e) {
    const { value } = e.detail;
    const { type } = e.target.dataset;
    this.setData({
      [`form.${type}`]: value,
    });
  },

  //   选择地址
  chooseAddress() {
    let that = this;
    wx.chooseLocation({
      success: (res) => {
        that.setData({
          "form.longitude": res.longitude, //经度
          "form.latitude": res.latitude, //纬度
          "form.parkAddress": res.address,
        });
      },
    });
  },

  // 核查日期
  bindDateCheckTime(e) {
    this.setData({
      "form.checkTime": e.detail.value,
    });
  },
  // 交警大队日期
  bindDatePoliceTime(e) {
    this.setData({
      "form.policeTime": e.detail.value,
    });
  },
  // 交管职能部门日期
  bindTrafficManagementTime(e) {
    this.setData({
      "form.trafficManagementTime": e.detail.value,
    });
  },
  // 局领导意见日期
  bindBureauOpinionTime(e) {
    this.setData({
      "form.bureauOpinionTime": e.detail.value,
    });
  },
  // 路内管理方式
  bindPickerManageType(e) {
    const index = e.detail.value;
    this.setData({
      manageType: this.data.manageTypeColumns[index].name,
      "form.manageType": this.data.manageTypeColumns[index].value,
    });
  },
  // 路内变更内容
  bindChangeType(e) {
    const index = e.detail.value;
    this.setData({
      changeType: this.data.changeTypeColumns[index].name,
      "form.changeType": this.data.changeTypeColumns[index].value,
    });
  },

  //   picker选择车场位置类型
  bindPickerLocationType(e) {
    const index = e.detail.value;
    index == 0
      ? this.setData({ isRoadRequired: true })
      : this.setData({ isRoadOffRequired: true });
    this.setData({
      parkLocationType: this.data.parkLocationTypeColumns[index].name,
      "form.parkLocationType": this.data.parkLocationTypeColumns[index].value,
    });
  },
  //   picker选择区域
  bindPickerJurisdiction(e) {
    const index = e.detail.value;
    this.setData({
      "form.jurisdiction": this.data.jurisdictionColumns[index],
      "form.parkJurisdiction": this.data.jurisdictionColumns[index],
    });
  },
  // 车场信息车辆停取方式
  bindPickerParkWay(e) {
    const index = e.detail.value;
    this.setData({
      parkWay: this.data.parkWayColumns[index].name,
      "form.parkWay": this.data.parkWayColumns[index].value,
    });
  },
  //定价方式
  bindPickerPricingMethod(e) {
    const index = e.detail.value;
    this.setData({
      pricingMethod: this.data.pricingMethodColumns[index].name,
      "form.pricingMethod": this.data.pricingMethodColumns[index].value,
    });
  },
  //车场产权
  bindPickerPricingMethod(e) {
    const index = e.detail.value;
    this.setData({
      pricingMethod: this.data.pricingMethodColumns[index].name,
      "form.pricingMethod": this.data.pricingMethodColumns[index].value,
    });
  },
  //车场产权
  bindPickerParkOwnership(e) {
    const index = e.detail.value;
    this.setData({
      parkOwnership: this.data.parkOwnershipColumns[index].name,
      "form.parkOwnership": this.data.parkOwnershipColumns[index].value,
    });
  },
  // 车场产权类型
  bindPickerParkOwnershipType(e) {
    const index = e.detail.value;
    this.setData({
      parkOwnershipType: this.data.parkOwnershipTypeColumns[index].name,
      "form.parkOwnershipType": this.data.parkOwnershipTypeColumns[index].value,
    });
  },
  // 所属交警大队
  bindPickerParkTrafficPolice(e) {
    const index = e.detail.value;
    this.setData({
      "form.trafficPolice": this.data.trafficPoliceColumns[index],
    });
  },
  // 停车场形式
  bindPickerOpenClosedType(e) {
    const index = e.detail.value;
    this.setData({
      openClosedType: this.data.openClosedTypeColumns[index].name,
      "form.openClosedType": this.data.openClosedTypeColumns[index].value,
    });
  },
  // 预约停车场类型
  bindPickerReserveType(e) {
    const index = e.detail.value;
    this.setData({
      reserveType: this.data.reserveTypeColumns[index].name,
      "form.reserveType": this.data.reserveTypeColumns[index].value,
    });
  },
  // 是否支持无感
  bindPickerIsAutoPay(e) {
    const index = e.detail.value;
    this.setData({
      isAutoPay: this.data.isAutoPayColumns[index].name,
      "form.isAutoPay": this.data.isAutoPayColumns[index].value,
    });
  },
  // 单双系统
  bindPickerSingleDoubleSystem(e) {
    const index = e.detail.value;
    this.setData({
      singleDoubleSystem: this.data.singleDoubleSystemColumns[index].name,
      "form.singleDoubleSystem": this.data.singleDoubleSystemColumns[index]
        .value,
    });
  },
  // 是否收费
  bindPickerChargingFlag(e) {
    const index = e.detail.value;
    this.setData({
      "form.chargingFlag": this.data.chargingFlagColumns[index],
    });
  },
  // 多选
  openMultiplePopup(e) {
    const { type, list } = e.currentTarget.dataset;
    const multipleList = this.data[list];
    this.setData({
      multipleList,
      multipleType: type,
      showMultiple: true,
    });
  },
  // 确认多选
  comfirmMultiple() {
    const { multipleResult, multipleType, multipleList } = this.data;
    if (multipleList.length > 0 && multipleResult.length > 0) {
      let value = " ";
      multipleList.forEach((item) => {
        multipleResult.forEach((child) => {
          if (child == item.value) {
            value = value + item.name;
          }
        });
      });
      this.setData({
        [`${multipleType}`]: value,
      });
    }
    this.setData({
      [`form.${multipleType}`]: multipleResult,
      showMultiple: false,
      multipleResult: [],
    });
  },
  noop() {},
  // 点击多选框
  toggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  // 多选
  onChangeCategoryList(event) {
    console.log(event);
    this.setData({
      multipleResult: event.detail,
    });
  },
  // 关闭多选
  onCloseMultiple() {
    this.setData({
      showMultiple: false,
      multipleResult: [],
    });
  },

  // 协议按钮
  setAgreementVip() {
    this.setData({
      agreementVip: !this.data.agreementVip,
    });
  },

  // 跳转协议页面
  toAgreement() {
    wx.navigateTo({
      url: "/pages/serviceAgreement/serviceAgreement",
    });
  },
  validateForm(formData) {
    if (!this.data.parkManagerId) {
      getApp().showToast("userId为null,请重新登录");
      wx.reLaunch({ url: "/pages/login/login" });
      return false;
    }
    // console.log(formData);
    if (!formData.parkLocationType) {
      getApp().showToast("请选择车场位置类型");
      return false;
    }
    if (!formData.corporateName) {
      getApp().showToast("请输入经营单位");
      return false;
    }
    // const socialCreditCode = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
    // if (
    //   !formData.socialCreditCode ||
    //   !socialCreditCode.test(formData.socialCreditCode)
    // ) {
    //   getApp().showToast("请输入正确的统一社会信用代码");
    //   return false;
    // }
    if (!formData.juridicalPersonName) {
      getApp().showToast("请输入法人姓名");
      return false;
    }
    if (!formData.juridicalPersonNo) {
      getApp().showToast("请输入法人身份证号");
      return false;
    }
    if (!formData.landlineMobile) {
      getApp().showToast("请输入办公监督电话");
      return false;
    }
    const phoneRegex = /^[1][3-9][0-9]{9}$/;
    if (!formData.telephone || !phoneRegex.test(formData.telephone)) {
      getApp().showToast("请输入正确的手机号");
      return false;
    }
    if (!formData.emailAddress) {
      getApp().showToast("请输入传真或邮箱");
      return false;
    }
    // 路内必填
    if (formData.parkLocationType == "1") {
      if (!formData.pointName) {
        getApp().showToast("请输入点位名称");
        return false;
      }
      if (!formData.berthType) {
        getApp().showToast("请输入泊位名称");
        return false;
      }
      if (!formData.roadType) {
        getApp().showToast("请输入占道类型");
        return false;
      }
      if (!formData.angleType) {
        getApp().showToast("请选择停放方式");
        return false;
      }
      if (!formData.manageType) {
        getApp().showToast("请选择管理方式");
        return false;
      }
      if (!formData.parkCode) {
        getApp().showToast("请输入车场编号");
        return false;
      }
      if (!formData.berthCode) {
        getApp().showToast("请输入泊位编号");
        return false;
      }
      if (!formData.berthSpace) {
        getApp().showToast("请输入泊位数");
        return false;
      }
      if (!formData.chargingFlag) {
        getApp().showToast("请输入是否收费");
        return false;
      }
    } else if (formData.parkLocationType == "2") {
      if (!formData.totalParkSpace) {
        getApp().showToast("请输入总车位数");
        return false;
      }
      if (!formData.parkWay) {
        getApp().showToast("请选择车辆停取方式");
        return false;
      }
      if (!formData.pricingMethod) {
        getApp().showToast("请选择定价方式");
        return false;
      }
      if (!formData.buildingType) {
        getApp().showToast("请选择所属建筑物类型");
        return false;
      }
      if (!formData.parkType) {
        getApp().showToast("请选择停车场类型");
        return false;
      }
      if (!formData.parkOwnership) {
        getApp().showToast("请选择车场产权");
        return false;
      }
      if (!formData.parkOwnershipType) {
        getApp().showToast("请选择车场产权类型");
        return false;
      }
      if (!formData.openClosedType) {
        getApp().showToast("请选择封闭形式");
        return false;
      }
      if (!formData.parkAngle) {
        getApp().showToast("请选择停放角度");
        return false;
      }
    }
    if (!formData.parkName) {
      getApp().showToast("请输入停车场名称");
      return false;
    }
    if (!formData.parkAddress) {
      getApp().showToast("请选择停车场地址");
      return false;
    }
    if (!formData.jurisdiction) {
      getApp().showToast("请选择区域");
      return false;
    }
    if (!formData.businessTime) {
      const businessTime = formData.businessTime || '';
      if (businessTime.indexOf("至") === -1 || businessTime.length < 3) {
        getApp().showToast("日期范围格式为--至--，例如:2022-12-31至2023-03-06或长期");
        return false;
      }
    }
    if (!formData.trafficPolice) {
      getApp().showToast("请选择所属交警大队");
      return false;
    }
    // 验证通过，返回 true
    return true;
  },
  onSubmit(e) {
    // 获取表单数据
    let formData = this.data.form;
    console.log(formData);
    // 路内停放方式
    if (Array.isArray(formData.angleType) && formData.angleType !== "string") {
      formData.angleType = formData.angleType.join(",");
    }
    // 收费区域
    if (
      Array.isArray(formData.chargingArea) &&
      formData.chargingArea !== "string"
    ) {
      formData.chargingArea = formData.chargingArea.join(",");
    }
    // 所属建筑物类型
    if (
      Array.isArray(formData.buildingType) &&
      formData.buildingType !== "string"
    ) {
      formData.buildingType = formData.buildingType.join(",");
    }
    // 停车场类型
    if (Array.isArray(formData.parkType) && formData.parkType !== "string") {
      formData.parkType = formData.parkType.join(",");
    }
    // 停放角度
    if (Array.isArray(formData.parkAngle) && formData.parkAngle !== "string") {
      formData.parkAngle = formData.parkAngle.join(",");
    }
    // 停车场设备
    if (
      Array.isArray(formData.intelligentDevice) &&
      formData.intelligentDevice !== "string"
    ) {
      formData.intelligentDevice = formData.intelligentDevice.join(",");
    }
    // if (!this.data.agreementVip) {
    //   getApp().showToast("请先阅读并同意车场服务协议");
    //   return false;
    // }

    console.log("格式化后传参", formData);
    if (this.validateForm(formData)) {
      this.addParkInfo(formData);
    }
    // 阻止表单默认提交行为
    return false;
  },
  // 添加车场
  async addParkInfo(formData) {
    try {
      this.setData({
        btnDisblay: true,
      });
      await addRecordApprovalApi(formData);
      getApp().showToast("添加成功!");
      this.onReset();
      // timeId = setTimeout(() => {
      //   wx.navigateBack({
      //     delta: 1,
      //   });
      // }, 1000);
    } catch (error) {
      console.log(error);
      getApp().showToast(error);
      // getApp().showToast("添加失败,请重试!");
    } finally {
      this.setData({
        btnDisblay: false,
      });
    }
  },
  //   表单重置
  onReset() {
    this.setData({
      form: {},
      parkLocationType: "",
      angleType: "",
      changeType: "",
      manageType: "",
      chargingArea: "",
      parkWay: "",
      pricingMethod: "",
      buildingType: "",
      parkType: "",
      parkOwnership: "",
      parkOwnershipType: "",
      openClosedType: "",
      parkAngle: "",
      intelligentDevice: "",
      reserveType: "",
      singleDoubleSystem: "",
      isAutoPay: "",
    });
  },
});
